import React, { useState, useEffect } from 'react';
import styles from './index.less';
import { Button, DatePicker, Select, Space, Spin, Table, Row, Col, Drawer } from 'antd';
import moment from 'moment';
import { tableLocale } from '@/tool/components/PageEmpty';
import { TRMessage } from '#/components';
import { UploadOutlined, FileTextOutlined } from '#/utils/antdIcons';
import { useTRState, useStaticState } from '#/utils/trHooks.jsx';

import plan_icon_dark from '@/assets/img/plan_icon_dark.png';
import { export_json_to_excel } from '@/utils/fileExport';
import { TjChart } from '@/pages/ETrade/components';

import { getTableColumns, charts, getChartOption } from './helper';
import { getMarketClearingList, getSpotTradingBriefingList } from './services';
import { useThemeChange } from '@/hooks';

const getDateRange = () => {
  return [moment().add(-7, 'day'), moment().add(-1, 'day')];
};

export default ({ power, buttonPermissions }) => {
  let _st = useStaticState({
    formValue: {
      startDate: '', // 开始日期
      endDate: '', // 结束日期
      marketId: '', // 交易中心编码
      provinceId: '', // 省份ID
    },
    marketName: '', // 展示使用: 交易中心名称
  }); // 用过的表单
  const [state, setState] = useTRState({
    // buttonPower
    canExport: buttonPermissions.some((x) => x.menuCode === 'ShiChangChuQingGaiKuangDaoChu'),
    // form
    marketItem: power[0],
    dates: getDateRange(),
    // result
    loading: true,
    isEmpty: false,
    chartData: [], // 图
    tableData: [], // 表
    briefingData: [], // 原始交易简报
    drawerVisible: false, // 控制交易简报提示
  });

  React.useEffect(() => {
    _onFinish();
  }, []);

  const _fetchData = async () => {
    setState({ loading: true });
    const params = _st.formValue;
    const res = await getMarketClearingList(params);
    let resData = {};
    if (params.marketId === 'PDBLJ' || params.marketId === 'PXBNX') {
      resData = res?.data?.resultMap || {};
    } else {
      resData = res?.resultMap || {};
    }
    fmtData(resData);
    setState({ loading: false });
    if (params.provinceId === '14') {
      // 山西有
      _getBriefingList(params);
    }
  };

  // 获取原始简报
  const _getBriefingList = async (params) => {
    const briefingData = (await getSpotTradingBriefingList(params))?.resultList || [];
    setState({
      briefingData,
    });
  };

  /** methods */
  const fmtData = (data) => {
    let totalMap = {};
    let fixNum = {};
    let chartData = [];
    const { startDate, endDate } = _st.formValue;
    const days = moment(endDate).diff(moment(startDate), 'day');
    for (let i = 0; i <= days; i++) {
      const date = moment(startDate).add(i, 'day');
      const dateKey = date.format('YYYY-MM-DD');
      let temp = {};
      for (const k in data) {
        for (const key in data[k] || {}) {
          let value = data[k][key][dateKey];
          // 记录保留小数位
          if (!fixNum[key] && typeof value === 'string') {
            fixNum[key] = value.split('.')?.[1]?.length || 0;
          }
          // 求和
          if (typeof totalMap[key] === 'undefined') {
            totalMap[key] = 0;
          }
          totalMap[key] += Number(value) || 0;
          temp[key] = value;
        }
      }
      temp['date'] = date.format('YYYYMMDD');
      chartData.push(temp);
    }
    let totalItem = { date: '合计' };
    if (chartData.length > 0) {
      for (const k in totalMap) {
        totalItem[k] = _.round(totalMap[k] / chartData.length, fixNum[k]).toFixed(fixNum[k]);
      }
    }
    setState({
      chartData,
      tableData: [totalItem, ...chartData],
    });
  };

  const _onFinish = () => {
    // 提交查询表单
    _st.formValue = {
      startDate: state.dates[0].format('YYYY-MM-DD'), // 开始日期
      endDate: state.dates[1].format('YYYY-MM-DD'), // 结束日期
      marketId: state.marketItem.marketId, // 交易中心编码
      provinceId: state.marketItem.provinceId, // 省份ID
    };
    _st.marketName = state.marketItem.marketName; // 展示使用: 交易中心名称
    _fetchData();
  };

  const _onReset = async () => {
    // 重置
    setState({
      marketItem: power[0],
      dates: getDateRange(),
    });
    _st.formValue = {
      startDate: getDateRange()[0].format('YYYY-MM-DD'), // 开始日期
      endDate: getDateRange()[1].format('YYYY-MM-DD'), // 结束日期
      marketId: power[0].marketId, // 交易中心编码
      provinceId: power[0].provinceId, // 省份ID
    };
    _st.marketName = power[0].marketName; // 展示使用: 交易中心名称
    _fetchData();
  };

  // 导出数据
  const exportFile = () => {
    if (!state.canExport) return TRMessage.info('请联系管理员获取相关权限');
    const { startDate, endDate } = _st.formValue;
    const filename = `${_st.marketName}-${startDate}-${endDate}-市场出清概况`;
    let params = {};
    if (_st.formValue.marketId === 'PDBLJ') {
      params = {
        multiHeader: [
          [
            '日期',
            '火电开机台数',
            '日前现货市场出清价格',
            '',
            '',
            '实时现货市场出清价格',
            '',
            '',
            '省内负荷-日前',
            '',
            '省内负荷-实时',
            '',
            '省内负荷偏差',
            '',
            '联络线外送-日前',
            '',
            '联络线外送-实时',
            '',
          ],
        ],
        header: [],
        data: [],
        merges: ['A1:A2', 'B1:B2', 'C1:E1', 'F1:H1', 'I1:J1', 'K1:L1', 'M1:N1', 'O1:P1', 'Q1:R1'],
        filename,
      };
    } else if (_st.formValue.marketId === 'PXBNX') {
      params = {
        multiHeader: [
          [
            '日期',
            '日前现货市场出清价格',
            '',
            '',
            '实时现货市场出清价格',
            '',
            '',
            '省内负荷-日前',
            '',
            '省内负荷-实时',
            '',
            '省内负荷偏差',
            '',
            '联络线外送-日前',
            '',
            '联络线外送-实时',
            '',
          ],
        ],
        header: [],
        data: [],
        merges: ['A1:A2', 'B1:D1', 'E1:G1', 'H1:I1', 'J1:K1', 'L1:M1', 'N1:O1', 'P1:Q1', 'R1:S1'],
        filename,
      };
    } else {
      params = {
        multiHeader: [
          [
            '日期',
            '火电开机台数',
            '机组运行容量',
            '日前现货市场出清价格',
            '',
            '',
            '实时现货市场出清价格',
            '',
            '',
            '省内负荷-日前',
            '',
            '省内负荷-实时',
            '',
            '省内负荷偏差',
            '',
            '联络线外送-日前',
            '',
            '联络线外送-实时',
            '',
          ],
        ],
        header: [],
        data: [],
        merges: [
          'A1:A2',
          'B1:B2',
          'C1:C2',
          'D1:F1',
          'G1:I1',
          'J1:K1',
          'L1:M1',
          'N1:O1',
          'P1:Q1',
          'R1:S1',
        ],
        filename,
      };
    }
    const filterVal = [];
    const tableColumns = getTableColumns(_st.formValue.marketId);
    tableColumns.map((item) => {
      if (item?.children?.length) {
        item.children.map((childItem) => {
          filterVal.push(childItem.dataIndex);
          params.header.push(childItem.title);
        });
      } else {
        filterVal.push(item.dataIndex);
        params.header.push(item.title);
      }
    });
    params.data = state.tableData.map((v) => filterVal.map((j) => (v ? v[j] : '-')));
    export_json_to_excel(params);
  };

  const toogleDrawer = () => {
    // 展示/关闭交易简报
    setState({
      drawerVisible: !state.drawerVisible,
    });
  };

  /** render */

  const ChartBox = ({ x }) => {
    const [config, setConfig] = useState();
    const { theme } = useThemeChange();

    useEffect(() => {
      if (x) {
        setConfig(getChartOption(state.chartData, x));
      }
    }, [x]);
    useEffect(() => {
      if (x) {
        setTimeout(() => {
          setConfig(getChartOption(state.chartData, x));
        }, 1);
      }
    }, [theme]);
    return <TjChart option={config} group="MarketClearing" style={{ height: '204px' }} />;
  };

  const _renderData = React.useMemo(() => {
    return (
      <Row gutter={[24, 24]}>
        {charts.map((x, idx) => (
          <Col span={12} key={idx}>
            <div className={styles.chartTitle}>
              <div className={styles.title}>{x.title}</div>
              <div className={styles.unit}>{x.unit}</div>
            </div>
            {/* <TjChart
              option={getChartOption(state.chartData, x)}
              group="MarketClearing"
              style={{ height: '204px' }}
            /> */}
            <ChartBox x={x} />
          </Col>
        ))}
        <Col span={24}>
          <Table
            className={styles.RollingTable}
            columns={getTableColumns(_st.formValue.marketId)}
            locale={tableLocale}
            dataSource={state.tableData}
            rowKey="date"
            rowClassName={(r) => (r.date === '合计' ? styles.total : '')}
            bordered
            scroll={state.tableData.length > 16 ? { x: 600, y: 500 } : { x: 600 }}
            pagination={false}
          />
        </Col>
      </Row>
    );
  }, [state.chartData, state.tableData]);

  return (
    <div className={styles.content}>
      <div className={styles.head}>
        <Space size={16} wrap>
          <Select
            style={{ width: 200 }}
            value={state.marketItem.value}
            options={power}
            optionFilterProp="label"
            showSearch
            showArrow
            onChange={(e, marketItem) => setState({ marketItem })}
          />
          <DatePicker.RangePicker
            style={{ width: 216 }}
            value={state.dates}
            separator="-"
            format={'YYYYMMDD'}
            disabledDate={(v) => v > moment()}
            allowClear={false}
            onChange={(dates) => setState({ dates })}
          />
          <Space size={16}>
            <Button
              style={{ width: 98, height: 32 }}
              type="primary"
              disabled={state.loading}
              onClick={_onFinish}
            >
              查询
            </Button>
            <Button style={{ width: 98, height: 32 }} ghost onClick={_onReset}>
              重置
            </Button>
          </Space>
        </Space>
        <Space size={16} wrap>
          {_st.formValue.marketId !== 'PDBLN' &&
            _st.formValue.marketId !== 'PDBLJ' &&
            _st.formValue.marketId !== 'PXBNX' && (
              <Button
                style={{ padding: 0 }}
                type="link"
                icon={<FileTextOutlined />}
                disabled={_st.formValue.provinceId !== '14' || !state.briefingData?.length}
                onClick={toogleDrawer}
              >
                查看原始简报
              </Button>
            )}
          <Button
            style={{ padding: 0 }}
            type="link"
            icon={<UploadOutlined />}
            disabled={!state.tableData.length}
            onClick={exportFile}
          >
            导出
          </Button>
        </Space>
      </div>

      <Spin spinning={state.loading} wrapperClassName={styles.main}>
        {_renderData}
      </Spin>

      <Drawer
        visible={state.drawerVisible}
        title={
          <div className={styles.drawerTitle}>
            <img src={plan_icon_dark} style={{ marginRight: 8 }} />
            现货交易简报
          </div>
        }
        placement={'right'}
        width={'62.5%'}
        destroyOnClose={true}
        onClose={toogleDrawer}
      >
        <div className={styles.drawerBody}>
          <div className={styles.head}>
            <div className={styles.date} />
            <div>日前交易简报</div>
            <div>日内交易简报</div>
          </div>
          <div className={styles.body}>
            {state.briefingData.map((item, idx) => {
              return (
                <div key={idx} className={styles.row}>
                  <div className={styles.date}>
                    {item?.date ? moment(item.date).format('YYYYMMDD') : item.date}
                  </div>
                  <div className={styles.txt}>{item?.dayAhead || ''}</div>
                  <div className={styles.txt}>{item?.realtime || ''}</div>
                </div>
              );
            })}
          </div>
        </div>
      </Drawer>
    </div>
  );
};
